package com.xuchang.match;

import com.lmax.disruptor.EventHandler;
import com.xuchang.disruptor.OrderEvent;
import com.xuchang.disruptor.OrderEventHandler;
import com.xuchang.model.OrderBooks;

import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.Map;
import java.util.Set;

@Configuration
@EnableConfigurationProperties(MatchEngineProperties.class)
public class MatchEngineAutoConfiguration {

    private final MatchEngineProperties properties;

    public MatchEngineAutoConfiguration(MatchEngineProperties properties) {
        this.properties = properties;
    }

    @Bean("eventHandlers")
    public EventHandler<OrderEvent>[] eventHandlers(){
        Map<String, MatchEngineProperties.CoinScale> symbols = properties.getSymbols();
        Set<Map.Entry<String, MatchEngineProperties.CoinScale>> entries = symbols.entrySet();

        EventHandler[] eventHandlers = new EventHandler[symbols.size()];

        int i = 0;
        for (Map.Entry<String, MatchEngineProperties.CoinScale> entry : entries) {
            String symbol = entry.getKey();
            MatchEngineProperties.CoinScale coinScale = entry.getValue();
            OrderBooks orderBooks = null;
            if(coinScale != null) {
                orderBooks=  new OrderBooks(symbol,coinScale.getCoinScale(),coinScale.getBaseCoinScale());
            }else {
                orderBooks = new OrderBooks(symbol);
            }
            eventHandlers[i++] = new OrderEventHandler(orderBooks);
        }

        return eventHandlers;
    }
 }
